package com.imchen.cms.interceptor;

import com.imchen.cms.model.*;
import com.imchen.cms.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author imchen
 * @create: 2019-01-15 16:34
 **/
@ControllerAdvice
public class RestAdvice implements ResponseBodyAdvice {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Map<String, Object> resultMap = new HashMap<>();
        if (o instanceof HashMap) {
            return new Result(1, "get map data", o);
        } else if (o instanceof Integer) {
            resultMap.put("count", o);
        } else if (o instanceof String) {
            resultMap.put("token", o);
        } else if (o instanceof Result) {
            return o;
        } else if (o instanceof org.springframework.core.io.Resource) {
            return o;
        } else {
            return new Result(200, "fetch object", o);
        }
        logger.debug("Class: {}  object: {}", aClass, o);
        return new Result(200, "exec method:" + methodParameter.getMethod(), resultMap);
    }
}